package com.Unidbg_hengdin.KD48;

import com.alibaba.fastjson.util.IOUtils;
import com.github.unidbg.AndroidEmulator;
import com.github.unidbg.Emulator;
import com.github.unidbg.Module;
import com.github.unidbg.arm.backend.Unicorn2Factory;
import com.github.unidbg.debugger.BreakPointCallback;
import com.github.unidbg.linux.android.AndroidEmulatorBuilder;
import com.github.unidbg.linux.android.AndroidResolver;
import com.github.unidbg.linux.android.dvm.*;
import com.github.unidbg.memory.Memory;
import com.github.unidbg.pointer.UnidbgPointer;
import com.github.unidbg.utils.Inspector;
import unicorn.ArmConst;

import java.io.File;


public class KD48  {
    private final AndroidEmulator emulator;
    private final VM vm;
    private final Module module;

//    private final DvmClass AuthorizeHelper;

    private final boolean logging;

    KD48(boolean logging) {
        this.logging = logging;

        emulator = AndroidEmulatorBuilder.for64Bit()
                .setProcessName("com.mfw.roadbook")
                .addBackendFactory(new Unicorn2Factory(true))
                .build(); // 创建模拟器实例，要模拟32位或者64位，在这里区分
        final Memory memory = emulator.getMemory(); // 模拟器的内存操作接口
        memory.setLibraryResolver(new AndroidResolver(23)); // 设置系统类库解析

        vm = emulator.createDalvikVM(); // 创建Android虚拟机
//        vm.setJni(this);
        vm.setVerbose(logging); // 设置是否打印Jni调用细节
        DalvikModule dm = vm.loadLibrary(new File("unidbg-android/src/test/java/com/Unidbg_hengdin/KD48/libencryptlib.so"), false); // 加载libttEncrypt.so到unicorn虚拟内存，加载成功以后会默认调用init_array等函数
        dm.callJNI_OnLoad(emulator); // 手动执行JNI_OnLoad函数
        module = dm.getModule(); // 加载好的libttEncrypt.so对应为一个模块

        // Java_com_mfw_tnative_AuthorizeHelper_xAuthencode
//        AuthorizeHelper = vm.resolveClass("com/mfw/tnative/AuthorizeHelper");
    }

    void destroy() {
        IOUtils.close(emulator);
        if (logging) {
            System.out.println("destroy");
        }
    }

    public static void main(String[] args) throws Exception {
        com.Unidbg_hengdin.KD48.KD48 test = new com.Unidbg_hengdin.KD48.KD48(true);

        test.callFunc();

        test.destroy();
    }

    void callFunc() {
        String data = "171161380216958a09e40a6e941d7b9b7c24a0d0e1637";
        UnidbgPointer md5Ctx = emulator.getMemory().malloc(200,false).getPointer();
        module.callFunction(emulator,0x1EAD0,md5Ctx);

        UnidbgPointer result = emulator.getMemory().malloc(200,false).getPointer();



        UnidbgPointer pwd = emulator.getMemory().malloc(200,false).getPointer();
        byte[] pwdByte = data.getBytes();
        pwd.write(pwdByte);

//        module.callFunction(emulator,0x1FA38,md5Ctx,pwd,pwdByte.length,result);
        module.callFunction(emulator,0x43340,md5Ctx,pwd,pwdByte.length,result);
        module.callFunction(emulator,0x43350,result);

        Inspector.inspect(result.getByteArray(0,32),"reslut");
    }



}
